<template>
  <view class="page-content">
    <view class="predetermine-tab">
      <view
        class="predetermine-tab-item"
        :class="isCurrent == item.id ? 'predetermine-tab-item-current ' : ''"
        v-for="item in tabs"
        :key="item.id"
        @click="selectProject(item)"
        >{{ item.name }}</view
      >
    </view>
    <view class="predetermine-check">
      <view class="predetermine-check-title"> 服务时段 </view>
      <view class="predetermine-check-main">
        <up-radio-group
          v-model="radiovalue"
          placement="column"
          iconPlacement="right"
        >
          <view
            class="predetermine-check-item"
            v-for="(item, index) in radiolist"
            :key="index"
          >
            <up-radio
              activeColor="#2cdeb4"
              inactiveColor="#2cdeb4"
              labelColor="#2cdeb4"
              :customStyle="{ marginBottom: '8px' }"
              :label="item.name"
              :name="item.id"
            >
            </up-radio>
          </view>
        </up-radio-group>
      </view>
      <view class="predetermine-check-title"> 服务项目 </view>
      <view class="predetermine-check-content">
        <up-cell-group :border="false">
          <up-cell
            :title="titleServeName ? titleServeName : '选择服务项目'"
            :titleStyle="{ color: '#ccc' }"
            :rightIconStyle="{ color: '#ccc' }"
            isLink
            :border="false"
            @click="openProject(1, '选择服务项目')"
          ></up-cell>
        </up-cell-group>
      </view>
    </view>
    <view class="predetermine-time">
      <view class="predetermine-title"> 服务周期 </view>
      <view class="predetermine-check-title"> 服务时长(天) </view>
      <view class="predetermine-check-content">
        <!-- <up-cell
          :title="'选择服务时长(' + (radiovalue == 1 ? '天' : '月') + ')'"
          :titleStyle="{ color: '#ccc' }"
          :rightIconStyle="{ color: '#ccc' }"
          isLink
          :border="false"
        ></up-cell> -->
        <up-input
          v-model="serviceDay"
          placeholder="请输入需要服务的天数"
          type="number"
          border="none"
          clearable
        ></up-input>
      </view>
      <view class="predetermine-check-title"> 开始时间 </view>
      <view class="predetermine-check-content">
        <up-cell
          :title="calendarName ? calendarName : '选择开始时间'"
          :titleStyle="{ color: '#ccc' }"
          :rightIconStyle="{ color: '#ccc' }"
          isLink
          :border="false"
          @click="calendarHide = true"
        ></up-cell>
      </view>
    </view>
    <view class="predetermine-time">
      <view class="predetermine-title"> 基本信息 </view>
      <view class="predetermine-check-title"> 被护理人 </view>
      <view class="predetermine-check-content">
        <up-cell
          :title="titleByNurseName ? titleByNurseName : '选择被护理人'"
          :titleStyle="{ color: '#ccc' }"
          :rightIconStyle="{ color: '#ccc' }"
          isLink
          :border="false"
          @click="openProject(2, '选择被护理人')"
        ></up-cell>
      </view>
      <view class="predetermine-check-title"> 选择地址 </view>
      <view class="predetermine-check-content">
        <up-cell
          :title="
            titleByNurseAddressName
              ? titleByNurseAddressName
              : '选择被护理人所在地址'
          "
          :titleStyle="{ color: '#ccc' }"
          :rightIconStyle="{ color: '#ccc' }"
          isLink
          @click="openProject(3, '选择服务地址')"
          :border="false"
        ></up-cell>
      </view>
      <view class="predetermine-check-title"> 注意事项 </view>
      <view class="predetermine-check-content">
        <up-textarea
          v-model="remark"
          placeholder="请输入需要注意的事项"
          autoHeight
        ></up-textarea>
      </view>
    </view>
    <view class="predetermine-buttom footer">
      <view class="predetermine-buttom-btn">
        <up-button
          type="primary"
          :text="'立即预订(' + MoneyCount() + ')'"
          @click="PayOrder()"
        ></up-button>
      </view>
    </view>
    <up-popup
      :show="serviceHide"
      :round="10"
      :closeable="true"
      mode="bottom"
      @close="close"
      @open="open"
    >
      <uni-nav-bar :title="comTypesName" :border="false"></uni-nav-bar>
      <ServiceProject
        v-if="serviceHide && comTypes == 1"
        :list="tabs"
        :isCurrent="isCurrent"
        :serveId="serveId"
        @update:updateProjectName="
          (ev) => (
            ((titleServeName = ev.name), (money = ev.value), (serveId = ev.id)),
            (serviceHide = false)
          )
        "
      />
      <ByNurse
        v-if="serviceHide && comTypes == 2"
        @update:updateByNurse="
          (ev) => (
            ((beNurseId = ev.id), (titleByNurseName = ev.name)),
            (serviceHide = false)
          )
        "
      />
      <ByNurseAddress
        v-if="serviceHide && comTypes == 3"
        @update:updateByNurseAddress="
          (ev) => (
            ((beNurseAddressId = ev.id),
            (titleByNurseAddressName = ev.detailAddress)),
            (serviceHide = false)
          )
        "
      />
      <view class="get-phone" v-if="serviceHide && comTypes == 4">
        <button
          class="get-phone-btn"
          open-type="getPhoneNumber"
          @getphonenumber="getPhoneNumber"
        >
          点击获取手机号
        </button>
      </view>
    </up-popup>
    <up-calendar
      :show="calendarHide"
      @confirm="confirm"
      @close="calendarHide = false"
    ></up-calendar>
  </view>
</template>

<script setup>
import { onMounted, ref } from "vue";

import { CreateOrder, GetUserPhone, GetServiceType } from "@/api/common.js";
import {
  GetLoginInfo, // 获取用户信息
} from "@/api/common.js";
import { getStorageData, setStorageData } from "@/utils/storageData.js";

import ServiceProject from "@/pages/predetermine/serviceProject.vue";
import ByNurse from "@/pages/predetermine/byNurse.vue";
import ByNurseAddress from "@/pages/predetermine/byNurseAddress.vue";

let isCurrent = ref(1);
let comTypes = ref(1);
let money = ref(0);
let serveId = ref("");

let tabs = ref([
  {
    id: 1,
    name: "住院护理",
  },
  {
    id: 2,
    name: "居家陪护",
  },
]);

let radiovalue = ref(2);

let radiolist = ref([
  // {
  //   id: 1,
  //   name: "小时陪护",
  // },
  {
    id: 2,
    name: "全天陪护",
  },
]);

let serviceDay = ref(0);

const props = defineProps({
  types: String,
});

// 获取手机号
const getPhoneNumber = async (ev) => {
  let { encryptedData, iv } = ev.detail;
  let params = {
    encryptedData,
    iv,
  };
  uni.login({
    provider: "weixin",
    onlyAuthorize: true, // 微信登录仅请求授权认证
    success: async function (event) {
      console.log(event, "event");
      try {
        params.code = event.code;
        uni.showLoading({
          title: "加载中",
        });
        let phone = await GetUserPhone(params);
        let us = await GetLoginInfo();
        us.data = phone.data;
        console.log(us, "phon111e");
        setStorageData("userInfo", JSON.stringify(us.data));
        uni.hideLoading();
        serviceHide.value = false;
      } catch (error) {
        serviceHide.value = false;
        uni.hideLoading();
      }
      // let params = {
      //   code: event.code,
      //   encryptedData: res.encryptedData,
      //   iv: res.iv,
      // };
      // try {
      //   uni.showLoading({
      //     title: "加载中",
      //   });
      //   let { data } = await UserLogin(params);
      //   setStorageData("token", data.token);
      //   setStorageData("loginInfo", data);
      //   let { data: userInfo } = await GetLoginInfo();
      //   setStorageData("userInfo", JSON.stringify(userInfo));
      //   uni.hideLoading();
      //   uni.switchTab({
      //     url: "/pages/home/index",
      //   });
      // } catch (error) {
      //   uni.hideLoading();
      // }
    },
    fail: function (err) {
      serviceHide.value = false;
      // 登录授权失败
      // err.code是错误码
    },
  });
};

let beNurseId = ref("");
let beNurseAddressId = ref("");
let remark = ref("");
const PayOrder = async () => {
  let userInfo = getStorageData("userInfo");
  console.log(userInfo, "userInfo");
  if (!userInfo) {
    uni.showToast({
      icon: "none",
      title: "请先登录",
    });
    setTimeout(() => {
      uni.navigateTo({
        url: "/pages/login/index",
      });
    }, 1000);
    return;
  }
  if (userInfo) {
    let us = JSON.parse(userInfo);
    if (!us.phone) {
      comTypes.value = 4;
      comTypesName.value = "需要获取您的手机号";
      serviceHide.value = true;
      return;
    }
  }
  let params = {
    openid: JSON.parse(userInfo)["unionid"],
    goodsName: isCurrent.value == 1 ? "住院护理" : "居家陪护", // 商品名称
    goodsType: isCurrent.value, // 商品类型
    serviceProject: titleServeName.value, // 服务项目
    serviceDay: serviceDay.value, // 服务时长天
    startTime: calendarName.value, // 服务开始时间
    beNurseId: beNurseId.value, // 被护理人Id
    beNurseAddressId: beNurseAddressId.value, // 被护理人地址
    serveId: serveId.value,
    remark: remark.value,
  };
  if (!isCurrent.value) {
    uni.showToast({
      icon: "none",
      title: "请选择护理类型",
    });
    return;
  }
  if (!titleServeName.value) {
    uni.showToast({
      icon: "none",
      title: "请选择服务项目",
    });
    return;
  }
  if (!titleServeName.value) {
    uni.showToast({
      icon: "none",
      title: "请输入服务时长",
    });
    return;
  }
  if (!calendarName.value) {
    uni.showToast({
      icon: "none",
      title: "请输入服务开始时间",
    });
    return;
  }
  if (!beNurseId.value) {
    uni.showToast({
      icon: "none",
      title: "请选择被护理人",
    });
    return;
  }
  if (!beNurseAddressId.value) {
    uni.showToast({
      icon: "none",
      title: "请选择被护理人地址",
    });
    return;
  }
  uni.showLoading({
    title: "加载中",
  });
  try {
    let { data } = await CreateOrder(params);
    wx.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.paySign,
      success(res) {
        console.log(res, "res", data);
        uni.hideLoading();
        uni.redirectTo({
          url: "/pages/paySuccess/index?orderId=" + data.id,
        });
      },
      fail(res) {
        uni.hideLoading();
      },
    });
  } catch (error) {
    uni.hideLoading();
  }
};

let serviceHide = ref(false);

let comTypesName = ref();
let titleByNurseName = ref(""); // 被护理人
let titleByNurseAddressName = ref(""); // 被护理人地址
const openProject = (types, title) => {
  comTypes.value = types;
  comTypesName.value = title;
  serviceHide.value = true;
};

const selectProject = (item) => {
  isCurrent.value = item.id;
  titleServeName.value = "";
};

// 定义方法
const open = () => {
  // 打开逻辑，比如设置 show 为 true
  serviceHide.value = true;
  // console.log('open');
};

const close = () => {
  // 关闭逻辑，设置 show 为 false
  serviceHide.value = false;
  // console.log('close');
};

let curName = ref("轻症");

let titleServeName = ref("");

let calendarHide = ref(false);
let calendarName = ref("");

const confirm = (ev) => {
  calendarName.value = ev[0];
  calendarHide.value = false;
  console.log(ev, "选择日期");
};

const MoneyCount = () => {
  console.log(serviceDay.value, money, "serviceDay.value == 0|| money");
  if (serviceDay.value == 0 || money.value == 0) {
    return "0.00";
  } else {
    return serviceDay.value * money.value;
  }
};

// 获取护理类型
const GetServiceTypeData = async () => {
  let { data } = await GetServiceType();
  isCurrent.value = data[0].id;
  tabs.value = data;
  if (props.types == 1) {
    isCurrent.value = data[0].id;
  } else {
    isCurrent.value = data[1].id;
  }
};

onMounted(() => {
  GetServiceTypeData();
});
</script>

<style scoped lang="scss">
.page-content {
  padding: 20rpx 20rpx 200rpx 20rpx;
  min-height: 100vh;
  background: linear-gradient(
    to bottom,
    rgba(255, 255, 255, 1),
    rgba(0, 0, 0, 0.1)
  );
}
.predetermine-tab-item {
  background: #f3fefb;
  color: #1dcb91;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
  text-align: center;
  width: 50%;
}
.predetermine-tab-item-current {
  background: #1dcb91;
  color: #fff;
}
.predetermine-tab {
  display: flex;
  width: 100%;
  border-radius: 12rpx 12rpx 0 0;
  overflow: hidden;
}
.predetermine-check {
  padding: 20rpx;
}

.predetermine-check-title {
  font-size: 28rpx;
  color: #999;
  line-height: 1;
  margin: 20rpx 0;
}
.predetermine-check {
  background: #ffffff;
  padding: 20rpx;
  border-radius: 0 0 16rpx 16rpx;
}

.predetermine-check-main {
  background: #f3fefb;
  padding: 10rpx 30rpx;
  border-radius: 16rpx;
  overflow: hidden;
}
.predetermine-check-content {
  background: #f3fefb;
  border-radius: 16rpx;
  overflow: hidden;
  ::v-deep .u-input {
    padding: 26rpx 30rpx !important;
  }
}

.predetermine-title {
  font-weight: bold;
  margin-bottom: 10rpx;
  color: #1dcb91;
}

.predetermine-time {
  padding: 20rpx;
  background: #fff;
  border-radius: 16rpx;
  margin-top: 20rpx;
}
.u-textarea {
  border: none;
  background: #f3fefb !important;
}
.predetermine-buttom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  z-index: 99;
}
.predetermine-buttom-btn {
  padding: 20rpx;
}
.get-phone {
  padding: 20vh 10vw;
  .get-phone-btn {
    background: #1dcb91;
    color: #fff;
  }
}
</style>
